/**
 * Created by Administrator on 2017/1/10.
 */
var DBFactory = require('../conn/DBFactory');
var async = require('async');
var goodsDao = module.exports;

function now() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return currentdate;
}

goodsDao.updateExtActivityId = function(auctionId, activityId) {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log(error);
            return;
        } else {
            connection.query('update goods set extActivityId = ? where auctionId = ? ', [activityId, auctionId],
                function(err){
                    if(err){
                        console.log('获取货品失败');
                        connection.release();
                    } else {
                        console.log('更新成功！');
                        connection.release();
                    }
                });
        }
    });
}

goodsDao.batchCreate = function(data, id, info, cb){
    if(!data && !id ){
        cb(new Error(500));
    } else {
        DBFactory.getConnection(function(error, connection){
            if(error) {
                cb(error);
            } else{
                var sql = "replace into goods (" + goodsColumnNames() + ") VALUES ?";
                var goods = getGoodsInfo(data, id);
                if(goods.length > 0) {
                    connection.query(sql, [goods], function(err, result) {
                            if(err){
                                cb(err);
                                console.log("batchCreate : " + err);
                                connection.release();
                                return;
                            }
                            else if(result) {
                                cb(null);
                            }
                            connection.release();
                            return;
                        }
                    );
                } else {
                    connection.release();
                    return;
                }
            }
        });
    }
}

// 用户提交的商品   超过 15天   自动清除
goodsDao.expiredAuditGoods = function (cb) {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            cb(error);
            return;
        } else {
            var sql = 'delete from audit_goods where ' +
                ' (UNIX_TIMESTAMP( NOW()) - UNIX_TIMESTAMP(created_date) ) >= 1296000';
            connection.query(sql, [], function(err, result){
                if(err){
                    cb(err);
                    connection.release();
                } else {
                    var rows = {};
                    rows.expiredAuditGoods = result.affectedRows;
                    cb(null, rows);
                }
                connection.release();
                return;
            });
        }
    });
}

//商品更新
goodsDao.read20GoodsToUpdate = function (nextGid, cb) {
    // TODO: get some goods from db, they are 2 be updated;
    DBFactory.getConnection(function(error, connection){
        if(error) {
            cb(error);
            return;
        } else {
            connection.query('select id, auctionId, zkPrice, sellerId, hiddenActivityId, source, pdId, hiddenStartTime ' +
                'from goods where hiddenActivityId is not null and nextRefreshTime <= now() order by nextRefreshTime limit 20;', [nextGid],
                function(err, result){
                    if(err){
                        cb('获取货品失败');
                        connection.release();
                    } else {
                        cb(null, result);
                        connection.release();
                    }
                });
        }
    });
}

goodsDao.deleteAuctionIdFromDb = function (auctionId, cb) {
    // TODO: delete from db; use thisCb as callback
    DBFactory.getConnection(function(error, connection){
        if(error) {
            cb(error);
            return;
        } else {
            var sql = 'replace into expire_goods(`pictUrl`,`shopTitle`,`title`,`tkRate`,`tkCommFee`,`totalNum`,' +
                '`couponEffectiveStartTime`,`couponEffectiveEndTime`,`biz30day`,`zkPrice`,`auctionUrl`,`couponAmount`,' +
                '`hiddenActivityId`,`hiddenAmount`,`couponLeftCount`,`couponTotalCount`,`couponInfo`,`tag`,`auctionId`,' +
                '`match_content`,`isHot`,`isCheap`,`isHighScore`,`isHighCoupon`,`isTMall`,`isRecommend`,`adTitle`,`uid_insert`,' +
                '`sellerId`,`source`,`reservePrice`,`includeDxjh`,`auctionTag`,`userType`,`created_date`,`updated_date`,`eventCreatorId`,' +
                '`eventRate`,`maxTkRate`,`eventEndTime`,`realTkRate`,`tkType`,`fqCat`,`planLink`,`isBrand`,`activityType`,`hiddenStartTime`,' +
                '`hiddenEndTime`,`hiddenInfo`,`hiddenStartFee`,`hiddenLeftCount`,`hiddenTotalCount`,`nextRefreshTime`,`teamName`) select ' +
                '`pictUrl`,`shopTitle`,`title`,`tkRate`,`tkCommFee`,`totalNum`,`couponEffectiveStartTime`,`couponEffectiveEndTime`,`biz30day`,' +
                '`zkPrice`,`auctionUrl`,`couponAmount`,`hiddenActivityId`,`hiddenAmount`,`couponLeftCount`,`couponTotalCount`,`couponInfo`,`tag`,' +
                '`auctionId`,`match_content`,`isHot`,`isCheap`,`isHighScore`,`isHighCoupon`,`isTMall`,`isRecommend`,`adTitle`,`uid_insert`,`sellerId`,' +
                '`source`,`reservePrice`,`includeDxjh`,`auctionTag`,`userType`,`created_date`,`updated_date`,`eventCreatorId`,`eventRate`,`maxTkRate`,' +
                '`eventEndTime`,`realTkRate`,`tkType`,`fqCat`,`planLink`,`isBrand`,`activityType`,`hiddenStartTime`,`hiddenEndTime`,`hiddenInfo`,' +
                '`hiddenStartFee`,`hiddenLeftCount`,`hiddenTotalCount`,`nextRefreshTime`,`teamName` from goods where goods.auctionId = ? ';
            connection.query(sql, [auctionId], function(err){
                if(err) {
                    cb(err);
                    console.log(err);
                    connection.release();
                    return;
                } else {
                    connection.query('delete from goods where auctionId = ?;', [auctionId],
                        function(err, result){
                            if(err){
                                cb('删除货品失败' + err.message);
                                connection.release();
                                return
                            } else {
                                cb(null, result);
                                connection.release();
                                return;
                            }
                        });
                }
            });
        }
    });
}
goodsDao.deleteAuctionIdFromBoutiquePoll = function(auctionId, cb) {
    var sql = 'delete from boutique_pool where auctionId = ? ';
    DBFactory.getConnection(function(error, connection){
        if(error) {
            cb(error);
            return;
        } else {
            connection.query(sql, [auctionId], function(err){
                if(err) {
                    cb(err);
                    console.log(err);
                    connection.release();
                    return;
                } else {
                    cb(null);
                    connection.release();
                    return;
                }
            });
        }
    });
}
goodsDao.deleteByHiddenActivityIdFromDb = function (hiddenActivityId, cb) {
    // TODO: delete from db; use thisCb as callback
    DBFactory.getConnection(function(error, connection){
        if(error) {
            cb(error);
            return;
        } else {
            var sql = 'replace into expire_goods(`pictUrl`,`shopTitle`,`title`,`tkRate`,`tkCommFee`,`totalNum`,' +
                '`couponEffectiveStartTime`,`couponEffectiveEndTime`,`biz30day`,`zkPrice`,`auctionUrl`,`couponAmount`,' +
                '`hiddenActivityId`,`hiddenAmount`,`couponLeftCount`,`couponTotalCount`,`couponInfo`,`tag`,`auctionId`,' +
                '`match_content`,`isHot`,`isCheap`,`isHighScore`,`isHighCoupon`,`isTMall`,`isRecommend`,`adTitle`,`uid_insert`,' +
                '`sellerId`,`source`,`reservePrice`,`includeDxjh`,`auctionTag`,`userType`,`created_date`,`updated_date`,`eventCreatorId`,' +
                '`eventRate`,`maxTkRate`,`eventEndTime`,`realTkRate`,`tkType`,`fqCat`,`planLink`,`isBrand`,`activityType`,`hiddenStartTime`,' +
                '`hiddenEndTime`,`hiddenInfo`,`hiddenStartFee`,`hiddenLeftCount`,`hiddenTotalCount`,`nextRefreshTime`,`teamName`) select ' +
                '`pictUrl`,`shopTitle`,`title`,`tkRate`,`tkCommFee`,`totalNum`,`couponEffectiveStartTime`,`couponEffectiveEndTime`,`biz30day`,' +
                '`zkPrice`,`auctionUrl`,`couponAmount`,`hiddenActivityId`,`hiddenAmount`,`couponLeftCount`,`couponTotalCount`,`couponInfo`,`tag`,' +
                '`auctionId`,`match_content`,`isHot`,`isCheap`,`isHighScore`,`isHighCoupon`,`isTMall`,`isRecommend`,`adTitle`,`uid_insert`,`sellerId`,' +
                '`source`,`reservePrice`,`includeDxjh`,`auctionTag`,`userType`,`created_date`,`updated_date`,`eventCreatorId`,`eventRate`,`maxTkRate`,' +
                '`eventEndTime`,`realTkRate`,`tkType`,`fqCat`,`planLink`,`isBrand`,`activityType`,`hiddenStartTime`,`hiddenEndTime`,`hiddenInfo`,' +
                '`hiddenStartFee`,`hiddenLeftCount`,`hiddenTotalCount`,`nextRefreshTime`,`teamName` from goods where goods.hiddenActivityId = ?';
            connection.query(sql, [hiddenActivityId], function(err){
                if(err) {
                    cb(err);
                    console.log(err);
                    connection.release();
                    return;
                } else {
                    connection.query('delete from goods where hiddenActivityId = ?;', [hiddenActivityId],
                        function(err, result){
                            if(err){
                                cb('删除货品失败' + err.message);
                                connection.release();
                                return;
                            } else {
                                console.log('db  : ' + result.affectedRows);
                                cb(null, result);
                                connection.release();
                                return;
                            }
                        });
                }
            });
        }
    });
}
goodsDao.deleteByHiddenActivityIdFromBoutiquePoll = function(hiddenActivityId, cb) {
    var sql = 'delete from boutique_pool where hiddenActivityId = ? ';
    DBFactory.getConnection(function(error, connection){
        if(error) {
            cb(error);
            return;
        } else {
            connection.query(sql, [hiddenActivityId], function(err, result){
                if(err) {
                    cb(err);
                    console.log(err);
                    connection.release();
                    return;
                } else {
                    console.log( 'boutique_pool :' + result.affectedRows);
                    cb(null);
                    connection.release();
                    return;
                }
            });
        }
    });
}
goodsDao.updatebiz30daysAndPrice = function (auctionId, biz30days, zkPrice, seller_id, nick, cb) {
    // TODO: update to db; use thisCb as callback
    DBFactory.getConnection(function(error, connection){
        if(error) {
            cb(error);
            return;
        } else {
            connection.query('update goods set biz30day = ?, zkPrice = ?, sellerId = ?, shopTitle = ?, nextRefreshTime = now()   where auctionId = ?;',
                [biz30days, zkPrice, seller_id, nick, auctionId],
                function(err, result){
                    if(err){
                        cb('更新货品失败' + err.message);
                    } else {
                        cb(null, result);
                    }
                    connection.release();
                    return;
                });
        }
    });
}

function goodsColumnNames(){
    return "`pictUrl`,`shopTitle`,`title`,`tkRate`,`tkCommFee`," +
        "`totalNum`,`couponEffectiveStartTime`,`couponEffectiveEndTime`,`biz30day`," +
        "`tag`,`zkPrice`,`auctionUrl`,`couponAmount`,`hiddenActivityId`,`hiddenAmount`," +
        "`couponLeftCount`,`couponTotalCount`,`couponInfo`,`auctionId`," +
        "`match_content`,`isHot`,`isCheap`,`isHighScore`,`isHighCoupon`,`isRecommend`,`isTMall`," +
        "`adTitle`,`uid_insert`,`sellerId`,`source`,`reservePrice`,`includeDxjh`,`auctionTag`,`userType`,`updated_date`," +
        "`eventCreatorId`,`eventRate`,`eventEndTime`,`maxTkRate`,`realTkRate`," +
        "`tkType`,`fqCat`,`planLink`,`isBrand`, `activityType`, " +
        "`hiddenStartTime`,`hiddenEndTime`,`hiddenInfo`,`hiddenStartFee`, `hiddenLeftCount`, `hiddenTotalCount`, `nextRefreshTime`, `teamName`, `pdId`,`goodShortTitle`,`extActivityId`,`long_picurl`,`mp4Url`,`couponAfterpri`";
}

function goodsInfoColumn(theData, uid, isNew, isPD) {

    var good = [];

    if(theData.pictUrl == undefined) theData.pictUrl = null;
    if(theData.shopTitle == undefined) theData.shopTitle = null;
    if(theData.title == undefined) theData.title = null;
    if(theData.tkRate == undefined) {
        theData.tkRate = 0;
    } else {
        theData.tkRate = parseFloat(theData.tkRate);
    }
    if(theData.tkCommFee == undefined) theData.tkCommFee = 0;
    if(theData.totalNum == undefined) theData.totalNum = 0;
    if(theData.couponEffectiveStartTime == undefined || theData.couponEffectiveStartTime == "") theData.couponEffectiveStartTime = null;
    if(theData.couponEffectiveEndTime == undefined || theData.couponEffectiveEndTime == "") theData.couponEffectiveEndTime = null;
    if(theData.biz30day == undefined) theData.biz30day = 0;
    if(theData.tag == undefined) theData.tag = null;
    if(theData.zkPrice == undefined) theData.zkPrice = 0;
    if(theData.auctionUrl == undefined) theData.auctionUrl = null;
    if(theData.couponAmount == undefined) theData.couponAmount = 0;
    if(theData.hiddenUrl == undefined) theData.hiddenUrl = null;
    if(theData.hiddenAmount == undefined) theData.hiddenAmount = 0;
    if(theData.couponLeftCount == undefined) theData.couponLeftCount = 0;
    if(theData.couponTotalCount == undefined) theData.couponTotalCount = 0;
    if(theData.couponInfo == undefined) theData.couponInfo = null;
    if(theData.auctionId == undefined) theData.auctionId = null;
    if(theData.isHot == undefined) theData.isHot = 0;
    if(theData.isCheap == undefined) theData.isCheap = 0;
    if(theData.isHighScore == undefined) theData.isHighScore = 0;
    if(theData.isHighCoupon == undefined) theData.isHighCoupon = 0;
    if(isPD)  theData.isRecommend = 1;
    if(theData.isRecommend == undefined) theData.isRecommend = 0;

    var mtc = '';
    if(theData.title) mtc += theData.title;
    if(theData.shopTitle) mtc += theData.shopTitle;
    if(theData.tag) mtc += theData.tag;
    if(theData.goodShortTitle == undefined) {
        theData.goodShortTitle = null;
    } else {
        mtc += theData.goodShortTitle;
    }
    if(mtc) {
        theData.match_content = mtc;
    } else {
        theData.match_content = null;
    }

    if(parseInt(theData.isTMall) == 1  || parseInt(theData.userType) == 1) {
        theData.userType = 1;
        theData.isTMall = 1;
    } else {
        theData.userType = 0;
        theData.isTMall = 0;
    }


    if(theData.adTitle == undefined) theData.adTitle = null;
    if(theData.sellerId == undefined) theData.sellerId = null;
    if(isPD) {
        theData.source = 'HTK';
        theData.pdId = theData.id;
    }
    if(theData.source == undefined) theData.source = null;
    if(theData.reservePrice == undefined) theData.reservePrice = null;
    if(theData.includeDxjh == undefined) theData.includeDxjh = 0;
    if(theData.auctionTag == undefined) theData.auctionTag = null;

    if(theData.eventCreatorId == undefined) theData.eventCreatorId = null;
    if(theData.eventRate == undefined) {
        theData.eventRate = 0;
    } else {
        theData.eventRate = parseFloat(theData.eventRate)
    }
    if(theData.eventEndTime == undefined) theData.eventEndTime = null;
    if(theData.maxTkRate == undefined) {
        theData.maxTkRate = 0;
    } else {
        theData.maxTkRate = parseFloat(theData.maxTkRate);
    }

    if(theData.realTkRate == undefined) {
        theData.realTkRate = Math.max(theData.maxTkRate, theData.eventRate, theData.tkRate);
        if(theData.tkRate == theData.realTkRate){
            theData.tkType = '通用佣金';
        }
        else if(theData.tkRate == theData.eventRate){
            theData.tkType = '鹊桥活动';
        }
        else{
            theData.tkType = '定向计划';
        }
    }
    if(theData.tkRate == 0) {
        theData.tkRate = theData.realTkRate;
    }

    if(theData.fqCat == undefined) theData.fqCat = 14;
    if(theData.planLink == undefined) theData.planLink = null;
    if(theData.isBrand == undefined) theData.isBrand = 0;
    if(theData.activityType == undefined) theData.activityType = null;
    if(theData.nextRefreshTime) theData.nextRefreshTime = new Date(theData.nextRefreshTime);
    if(theData.teamName == undefined) theData.teamName = null;
    if(theData.pdId == undefined) theData.pdId = 0;
    if(theData.isRecommend == undefined) theData.isRecommend = 0;
    if(theData.hiddenEffectiveStartTime != undefined) {
        theData.hiddenStartTime = commonUtil.formatDate(new Date(theData.hiddenEffectiveStartTime));
    } else {
        theData.hiddenStartTime = theData.hiddenStartTime ?　theData.hiddenStartTime : null
    }
    if(theData.hiddenEffectiveEndTime != undefined) {
        theData.hiddenEndTime = commonUtil.formatDate(new Date(theData.hiddenEffectiveEndTime));
    } else {
        theData.hiddenEndTime = theData.hiddenEndTime ?　theData.hiddenEndTime : null
    }

    theData.extActivityId = theData.extActivityId ? theData.extActivityId : null;
    theData.long_picurl = theData.long_picurl ? theData.long_picurl : null;
    theData.mp4Url = theData.mp4Url ? theData.mp4Url : null;
    theData.couponAfterpri = theData.couponAfterpri ? theData.couponAfterpri : parseFloat(theData.zkPrice) - parseFloat(theData.hiddenAmount);

    good.push(theData.pictUrl);
    good.push(theData.shopTitle);
    good.push(theData.title);
    good.push(theData.tkRate);
    good.push(theData.tkCommFee);
    good.push(theData.totalNum);
    good.push(theData.couponEffectiveStartTime);
    good.push(theData.couponEffectiveEndTime);
    good.push(theData.biz30day);
    good.push(theData.tag);
    good.push(theData.zkPrice);
    good.push(theData.auctionUrl);
    good.push(theData.couponAmount);
    good.push(theData.hiddenActivityId);
    good.push(theData.hiddenAmount);
    good.push(theData.couponLeftCount);
    good.push(theData.couponTotalCount);
    good.push(theData.couponInfo);
    good.push(theData.auctionId);
    good.push(theData.match_content);
    good.push(theData.isHot);
    good.push(theData.isCheap);
    good.push(theData.isHighScore);
    good.push(theData.isHighCoupon);
    good.push(theData.isRecommend);
    good.push(theData.isTMall);
    good.push(theData.adTitle);
    good.push(uid);
    good.push(theData.sellerId);
    good.push(theData.source);
    good.push(theData.reservePrice);
    good.push(theData.includeDxjh);
    good.push(theData.auctionTag);
    good.push(theData.userType);
    good.push(now());
    good.push(theData.eventCreatorId);
    good.push(theData.eventRate);
    good.push(theData.eventEndTime);
    good.push(theData.maxTkRate);
    good.push(theData.realTkRate);
    good.push(theData.tkType);
    good.push(theData.fqCat);
    good.push(theData.planLink);
    good.push(theData.isBrand);
    good.push(theData.activityType);

    good.push(theData.hiddenStartTime);
    good.push(theData.hiddenEndTime);
    good.push(theData.hiddenInfo);
    good.push(theData.hiddenStartFee);
    good.push(theData.hiddenLeftCount);
    good.push(theData.hiddenTotalCount);
    good.push(theData.nextRefreshTime);
    good.push(theData.teamName);
    good.push(theData.pdId);
    good.push(theData.goodShortTitle);
    good.push(theData.extActivityId);
    good.push(theData.long_picurl);
    good.push(theData.mp4Url);
    good.push(theData.couponAfterpri);

    if(theData.id && !isNew) {
        good.push(theData.id);
    }
    return good;
}

//  获取多个商品的有效数据
function getGoodsInfo (data, id, isNew, isPD) {
    var goods = [];
    for(var i = 0; i < data.length; i++){
        if(data[i].auctionId && data[i].hiddenActivityId && parseFloat(data[i].zkPrice) - parseFloat(data[i].hiddenAmount) > 0) {
            var theData = data[i];
            goods.push(goodsInfoColumn(theData, id, isNew, isPD));
        }
    }
    return goods;
}

goodsDao.isExist = function (data, cb) {
    if(!data) {
        cb(new Error(500));
    } else {
        DBFactory.getConnection(function(error, connection){
            if(error){
                cb(error);
            } else {
                connection.query('select auctionId , hiddenActivityId , hiddenAmount , source , pdId, tkCommFee, realTkRate from goods where auctionId in ( ? ) ',[data.auctionIdList],
                function(err, result){
                    if(err) {
                        console.log(err);
                        cb(err);
                        connection.release();
                        return;
                    } else {
                        cb(null, result);
                        connection.release();
                    }
                });
            }
        });
    }
}

goodsDao.updateHiddenCoupon = function(data ,cb) {
    if(!data) {
        cb(new Error(500));
    } else {
        DBFactory.getConnection(function(error, connection) {
            if(error) {
                cb(error);
            } else {
                connection.query('update goods set ' +
                    'hiddenAmount = ?, hiddenStartTime = ?, hiddenEndTime = ?, hiddenInfo = ?, ' +
                    'hiddenStartFee = ?, hiddenLeftCount = ?, hiddenTotalCount = ?, ' +
                    'nextRefreshTime = now(), updated_date = now() ' +
                    'where hiddenActivityId = ?' ,
                    [data.couponAmount, data.couponEffectiveStartTime, data.couponEffectiveEndTime, data.couponInfo,
                        data.startFee, data.couponLeftCount, data.couponTotalCount,
                        data.activityId], function(e, result) {
                        if(e) {
                            cb(e);
                            console.log(e);
                        } else {
                            cb(null, result);
                        }
                        connection.release();
                        return;
                    });
            };
        });
    }
}

goodsDao.updateTag = function(tag, keyWord) {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log(error);
            return;
        } else {
            var sql = 'update goods set tag = ? where title like ? ';
            connection.query(sql, [tag, '%'+keyWord+'%'], function(err, result){
                    if(err){
                        console.log('修改标签失败！tag: '+ tag + ' err:' + err);
                        connection.release();
                    } else {
                        console.log('修改标签成功！');
                        console.log(result.affectedRows);
                        connection.release();
                    }
                });
        }
    });
}

goodsDao.delInvalidGoods = function() {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log(error);
            return;
        } else {
            var sql = 'delete from goods where zkPrice-hiddenAmount < 0';
            connection.query(sql, [], function(err, result){
                if(err){
                    console.log('delInvalidGoods err :' + err);
                    connection.release();
                } else {
                    console.log('删除无效商品成功！');
                    console.log(result.affectedRows);
                    connection.release();
                }
            });
        }
    });
}